<script setup lang="ts">
	import { ref } from 'vue'

	defineOptions({
		options: {
			styleIsolation: 'shared',
		},
		name: 'CustomPassword'
	})

	// 表单数据
	const loginForm = ref({
		mobile: '',
		password: ''
	})

	// 表单规则
	const rules = {
		mobile: {
			rules: [
				{ required: true, errorMessage: '请输入手机号' },
				{ pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' }
			]
		},
		password: {
			rules: [
				{ required: true, errorMessage: '请输入密码' },
				{ minLength: 6, errorMessage: '密码最少6位' }
			]
		}
	}

	// 协议勾选状态
	const agreed = ref(false)

	// 表单实例引用
	const form = ref<any>(null)

	// 登录方法
	const handleLogin = async () => {
		// 验证表单
		try {
			const valid = await form.value?.validate()
			if (!valid) return

			if (!agreed.value) {
				uni.showToast({
					title: '请先同意用户协议',
					icon: 'none'
				})
				return
			}

			// TODO: 调用登录接口
			const { mobile, password } = loginForm.value
			// const res = await login({ mobile, password })

			uni.showToast({
				title: '登录成功',
				icon: 'success'
			})

			// 登录成功后跳转
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}, 1500)

		} catch (error) {
			uni.showToast({
				title: '表单校验失败',
				icon: 'error'
			})
		}
	}
</script>

<template>
	<uni-forms class="login-form" ref="form" :model="loginForm" :rules="rules">
		<uni-forms-item name="mobile">
			<uni-easyinput
				v-model="loginForm.mobile"
				:input-border="false"
				:clearable="false"
				placeholder="请输入手机号"
				placeholder-style="color: #C3C3C5"
			/>
		</uni-forms-item>
		<uni-forms-item name="password">
			<uni-easyinput
				v-model="loginForm.password"
				type="password"
				placeholder="请输入密码"
				:input-border="false"
				placeholder-style="color: #C3C3C5"
			/>
		</uni-forms-item>
		<view class="agreement">
			<radio :checked="agreed" color="#16C2A3" @tap="agreed = !agreed" />
			我已同意
			<text class="link">用户协议</text>
			及
			<text class="link">隐私协议</text>
		</view>

		<button class="uni-button" @tap="handleLogin">登 录</button>
		<navigator hover-class="none" class="uni-navigator" url="/pages/login/forgot"> 忘记密码？ </navigator>
	</uni-forms>
</template>

<style lang="scss">
	@import './styles.scss';
</style>
